<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\SettingRepayRate
 *
 * @property int $id
 * @property string $channel_code 资金方编号,和setting_channel表进行关联
 * @property int $period 期数
 * @property float $lending_rate 贷款费率
 * @property float $insurance_rate 前置保险费
 * @property float $month_insurance_rate 月保险费率
 * @property float $manage_rate 管理费率
 * @property float $repayment_rate 提前还清手续费
 * @property float $fines_rate 逾期罚息利率
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereChannelCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereFinesRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereInsuranceRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereLendingRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereManageRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereMonthInsuranceRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate wherePeriod($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereRepaymentRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property float $insure_rate 保证险
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\SettingRepayRate whereInsureRate($value)
 */
class SettingRepayRate extends Model
{
    //
    protected $guarded = [
        'id'
    ];

    /**
     * Description: 获取列表
     * Author:lijiafei
     * @return array|\Illuminate\Database\Eloquent\Collection|static[]
     */
    public static function getRateList(){
        $settingSource = new SettingChannel();
        $settingSource->setConnection('backend');
        $channelList = $settingSource->select('channel_code','channel_name')->get();
        if(empty($channelList)){
            return [];
        }
        $period_range = SettingLoan::getPeriodRange();
        foreach ($channelList as $k => &$v){
            //把可选的期限返回回去
            $v['period_range'] = $period_range;
            $rateInfo = (new SettingRepayRate())->setConnection('backend')->where('channel_code',$v['channel_code'])->get();
            if($rateInfo){
                foreach ($rateInfo as $key => &$val){
                    //统一*100 变为百分比形式
                    $val["lending_rate"] = $val["lending_rate"]*100;
                    $val["insurance_rate"] = $val["insurance_rate"]*100;
                    $val["insure_rate"] = $val["insure_rate"]*100;//保证险
                    $val["month_insurance_rate"] = $val["month_insurance_rate"]*100;
                    $val["manage_rate"] = $val["manage_rate"]*100;
                    $val["repayment_rate"] = $val["repayment_rate"]*100;
                    $val["fines_rate"] = $val["fines_rate"]*100;
                }
                $v['rate_info'] = $rateInfo;
            }else{
                $v['rate_info'] = [];
            }
        }
        return $channelList;
    }

    public static function createRate($rateInfo){
        $result = self::validateRate($rateInfo);
        if($result !== 1){
            return $result;
        }
        $res = self::create($rateInfo);
        if($res){
            return $res->id;
        }else{
            return 0;
        }

    }

    public static function updateRate($rateInfo,$id){
        $result = self::validateRate($rateInfo,$id);
        if($result != 1){
            return $result;
        }
        $res = self::where('id',$id)->update($rateInfo);
        if($res){
            return 1;
        }else{
            return 0;
        }

    }

    protected static function validateRate($rateInfo,$id = 0){
        /*
         * 1.判断channel_code是否存在
         * 2.判断期限是否在范围内
         * 3.判断当前期数和资方编号是否在数据库中
         */
        $isHas = SettingChannel::hasChannelCode($rateInfo['channel_code']);
        if(!$isHas){
            return -1;
        }
        $isRange = SettingLoan::inPeriodRange($rateInfo['period']);
        if(!$isRange){
            return -2;
        }
        //判断期数是否一样
        $hasPeriod = self::hasPeriod($rateInfo['period'],$rateInfo['channel_code'],$id);
        if($hasPeriod){
            return -3;
        }
        return 1;
    }

    /**
     * 判断是否已经存在 特定 期数
     */
    public static function hasPeriod($period,$channel_code,$id = 0){
        $where = array(
            ['channel_code','=',$channel_code],
            ['period','=',$period]
        );
        if($id){
            $where[] = ['id','<>',$id];
        }
        $result = self::where($where)->first();
        return $result;
    }

    /**
     * Description: 通过渠道号和周期获取利率信息
     * Author:lijiafei
     * @param $channel string 渠道号
     * @param $period int 借款的周期
     * @return array 对应的配置信息
     */
    public static function getRateByChannl($channel,$period){
        $result =  self::select('lending_rate','insurance_rate','insure_rate','month_insurance_rate','manage_rate','repayment_rate','fines_rate') -> where('channel_code',$channel)->where('period',$period)->first();
        if(!$result){
//            Log::debug('获取费率:获取渠道号为' . $channel . '期数为' . $period . '期的费率没有');
            return ['lending_rate'=>0,'insurance_rate'=>0,'insure_rate' => 0,'month_insurance_rate'=>0,'manage_rate'=>0,'repayment_rate'=>0,'fines_rate'=>0];
        }
        return $result->toArray();
    }
}
